<?php

namespace app\admin\controller\union;
/* 超推每日收益 */

use app\admin\library\Auth;
use app\admin\model\Admin;
use app\admin\model\union\Guild;
use app\admin\model\union\GuildCashOut;
use app\admin\model\union\TmpSetting;
use app\common\controller\Backend;
use app\admin\model\union\GuildAccountDaily;
use app\admin\model\union\GuildWithdrawAccount;
use think\Db;
use think\Model;

class Daily extends Backend
{
    protected $model = null;
    protected $searchFields = '';
    protected $admin_id = null;
    protected $guild_id = 0;
    protected $guild_manage_id = 0;
    protected $procedures = 0.065;
    protected $week = 5;
    protected $period = 5;
    public function _initialize()
    {
        parent::_initialize();
        //获取后台登录管理员id
        $auth = Auth::instance();
        $this->admin_id = $auth->isLogin() ? $auth->id : 0;
        $this->assign('admin_id', $this->admin_id);
        $admin_row = Admin::get(intval($auth->id));
        $this->guild_id = $admin_row['guild_id'];
        $this->procedures = $admin_row['procedures'];
        $this->week = $admin_row['week'];
        $this->period = $admin_row['period'];
//        if($this->guild_id)$this->guild_manage_id = Guild::where('guild_id',$this->guild_id)->value('id');
        $this->model = new GuildAccountDaily();

    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        //查询二级超推
        $child_data = Guild::field('id')->where('parent_guild_id',$this->guild_id)->select()->toArray();
        if (!empty($child_data)){
            $child_id = array_column($child_data,'id');
        }

        if ($this->request->isAjax()) {

            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where2 = [];
            if ($this->guild_id)$where2['guild_manage_id'] = $this->guild_id;
            $list = $this->model->where($where);
            if (!empty($where2))$list = $list->where($where2);
            $list = $list->order($sort, $order)->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());

            foreach ($list->items() as $v){
                if (isset($child_id)){
                    $v->child_sum = round(GuildAccountDaily::where('guild_manage_id','in',$child_id)
                        ->where('dt','=',$v->dt)
                        ->value('sum(one_guild_income)'),2);
                }else{
                    $v->child_sum = 0;
                }
                $new_total = $v->msg_turnover + $v->voice_turnover+$v->gift_turnover + $v->video_turnover+$v->free_turnover;
                $v->total_turnover = $new_total;
                $v->count_sum = round($v->child_sum + $v->guild_share_income,2);

            }

            return json($result);
        }
        //查询所有的收益
        $child_sum = 0;
        if (isset($child_id))$child_sum = GuildAccountDaily::where('guild_manage_id','in',$child_id)
            ->value('sum(one_guild_income)');
        $total = GuildAccountDaily::where('guild_manage_id',$this->guild_id)->value('sum(guild_share_income)');
        $this->assign('total',$total+$child_sum);

        //可提现金额
        $day_num = (int)$this->period;
        $q_day = date("Y-m-d",strtotime("-$day_num day"));
        $total_out = 0;
        $total_data = GuildAccountDaily::field('id,guild_manage_id,guild_share_income,dt')->where('guild_manage_id',$this->guild_id)
            ->where('dt','<=',$q_day)
            ->where('out_status','in',[0,3])
            ->select();
        $dt_list = [];
        if ($total_data){
            foreach ($total_data as $v){
                $total_out+=$v->guild_share_income;
                $dt_list[] = $v->dt;
            }
        }
        $total_out = $total_out;
//        $dt_row = GuildAccountDaily::field('dt')->where('guild_manage_id',$this->guild_id)
//            ->where('out_status',1)
//            ->order('id desc')->find();
        $child_sum_out = 0;
        if (isset($child_id) && !empty($dt_list))
        {
            $child_sum_out = GuildAccountDaily::where('guild_manage_id','in',$child_id)
                ->where('dt','in',$dt_list)->value('sum(one_guild_income)');
//                 if ($dt_row)$child_sum_out = $child_sum_out->where('dt','>',$dt_row->dt);
//            $child_sum_out = $child_sum_out->value('sum(one_guild_income)');
        }

        $this->assign('total',round($total+$child_sum,2));
        $this->assign('quota',round($total_out+$child_sum_out,2));
        $this->assign('day',$q_day);

        $accountInfo = GuildWithdrawAccount::where(['guild_manage_id'=>$this->guild_id,'status'=>1])->find();
        if(!$accountInfo){
            $accountInfo = GuildCashOut::where(['guild_manage_id'=>$this->guild_id])->where('status','in','1,3')->order('id','desc')->find();
        }

        $accountInfo = $accountInfo ? $accountInfo->toArray() : ['out_type'=>0,'username'=>'','idcard'=>'','bank_name'=>'','payment'=>''];
        $this->assign('account_info',$accountInfo);
        return $this->view->fetch();
    }

    //提现
    public function cash_out(){
        $new_week = date('w');
        if ($this->week != $new_week){
            return ['ret' => 1, 'msg' => '暂时不能提现，不在提现日期！'];
        }
        $payment = input('payment','');
        $out_type = input('out_type',1);
        $username = input('username','');
        $idcard = input('idcard','');
        $bank_name = input('bank_name','');
        $day_num = (int)$this->period;//TmpSetting::getConf('period')??1;
        $q_day = date("Y-m-d",strtotime("-$day_num day"));
        $total_out = 0;
        $total_data = GuildAccountDaily::field('id,guild_manage_id,guild_share_income,dt')->where('guild_manage_id',$this->guild_id)
            ->where('dt','<=',$q_day)
            ->where('out_status','in',  [0,3]) //'0' : '未提现','1' :'已提现','2':'申请中','3':'失败'
            ->select();
        $guild_id_arr = [];
        $dt_list = [];
        if ($total_data){
            foreach ($total_data as $v){
                $total_out+=$v->guild_share_income;
                $guild_id_arr[] = $v->id;
                $dt_list[] = $v->dt;
            }
        }
//        $dt_row = GuildAccountDaily::field('dt')->where('guild_manage_id',$this->guild_id)
//            ->where('out_status',3)
//            ->order('id desc')->find();

        //查询二级超推
        $child_data = Guild::field('id')->where('parent_guild_id',$this->guild_id)->select()->toArray();
        if (!empty($child_data)){
            $child_id = array_column($child_data,'id');
        }

        $child_sum_out = 0;
        if (isset($child_id) && !empty($dt_list))
        {
            $child_sum_out = GuildAccountDaily::where('guild_manage_id','in',$child_id)
                    ->where('dt','in',$dt_list)->value('sum(one_guild_income)')??0;


        }

        $total = round(($total_out+$child_sum_out)/10, 2);

        if ($total <= 0 ){
            return ['ret' => 1, 'msg' => '没有提现金额，申请失败！'];
        }
        if($total < 100){
            return ['ret' => 1, 'msg' => '申请失败！,最低提现金额1000金币'];
        }
        //插入提现记录表
        $bool = false;
        Db::startTrans();
        try{
            $service_charges = $total * $this->procedures;
            $actual_amount = $total - $service_charges;
            GuildCashOut::create(['guild_manage_id'=>$this->guild_id,'amount'=>$total,'created_at'=>date('Y-m-d H:i:s'),'daily_id'=>implode(',',$guild_id_arr),'service_charges'=>$service_charges,'actual_amount'=>$actual_amount,'out_type'=>$out_type,'payment'=>$payment,'username'=>$username,'idcard'=>$idcard,'bank_name'=>$bank_name]);
            GuildAccountDaily::where('dt','in',$dt_list)->where('guild_manage_id',$this->guild_id)->update(['out_status'=>2]);
            $bool = true;
        }catch (\Exception $exception){
            $bool = false;
            Db::rollback();
        }
        if ($bool){
            return ['ret' => 0, 'msg' => '申请成功！'];
        }else{
            return ['ret' => 1, 'msg' => '申请失败！'];
        }
    }

}